package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.commit;
import com.cfets.annualAssessment.service.CommitService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by ShenYiChou on 2017/2/3.
 */
@Controller
@RequestMapping("/admin/commit")
@Log4j
public class CommitController {
    @Autowired
    private CommitService commitService;

    @RequestMapping("/index")
    public String index(Model model){
        return "commit";
    }

    @ModelAttribute("commit")
    public commit getCommit(){
        commit commit = new commit();
        try {
            List<commit> commitList = this.commitService.CommitList();
            if(commitList != null && commitList.size() > 0) {
                commit = commitList.get(0);
            }
        }catch (Exception e) {
            log.error("",e);
        }
        return commit;
    }
    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid commit commit, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String str=sdf.format(date);
        commit.setUpdate_time(str);
        boolean flag = false;
        if(commit.getId()!=null && commit.getId()!=0){
            flag = this.commitService.updateCommit(commit);
        }else {
            flag = this.commitService.newCommit(commit);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
    //前台承诺书rest
    @RequestMapping(value = "/restful",method = RequestMethod.GET)
    public ResponseEntity<?> RestCommit(){
        commit commit = new commit();
        List<commit> commitList = this.commitService.CommitList();
        if(commitList != null && commitList.size() > 0) {
            commit = commitList.get(0);
        }
        return new ResponseEntity<>(commit, HttpStatus.OK);
    }
}
